package com.pcy.codegenerator.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pcy.codegenerator.dao.GeneratorDao;
import com.pcy.codegenerator.utils.GenUtils;
import com.pcy.codegenerator.utils.GenUtils2;
import com.pcy.codegenerator.utils.PageUtils;
import com.pcy.codegenerator.utils.Query;
import com.pcy.codegenerator.utils.annotation.DataSourceTarget;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * @author 彭长云
 * @Description:
 * @date 2020/1/13 17:35
 */
@Service
public class GeneratorService {
    @Autowired
    private GeneratorDao generatorDao;
    @Autowired
    private DataSource dataSource;


    /**
     * 查询数据库表
     */
    @DataSourceTarget
    public PageUtils queryList(Query query) {
        Page<?> page = PageHelper.startPage(query.getPage(), query.getRows());
        List<Map<String, Object>> list = generatorDao.queryList(query);

        return new PageUtils(list, (int)page.getTotal());
    }

    /**
     * 返回生成的代码字符串
     */
    @DataSourceTarget
    public String generatorCode(String tableName,String template) {
        Map<String,Object> resultMap = new HashMap<>();
        //查询表信息
        Map<String, String> table = queryTable(tableName);
        //查询列信息
        List<Map<String, String>> columns = queryColumns(tableName);
        //生成代码
        return GenUtils2.generatorCode(table, columns, template);
    }

    /**
     * 用于下载
     */
    public byte[] generatorCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        for(String tableName : tableNames){
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            GenUtils.generatorCode(table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    @DataSourceTarget
    public Map<String, String> queryTable(String tableName) {
        return generatorDao.queryTable(tableName);
    }

    @DataSourceTarget
    public List<Map<String, String>> queryColumns(String tableName) {
        return generatorDao.queryColumns(tableName);
    }


    /**
     * 生成实体
     */
    public Object generateEntity(){

        return null;
    }
}
